// pages/users/yResult/index.js
import * as echarts from '../../../components/ec-canvas/echarts.min';
const {
  rpxTopx
} = require('../../../utils/util')
const {
  reviewDetail
} = require('../../../api/api')

function setOption(seriesData, chart, data) {
  let legendData = seriesData.map((item) => {
    return item.name
  })
  const option = {
    backgroundColor: "#F9F7FA",
    color: ["#DDD3DA"],
    radar: {
      radius: '44%',
      nameGap: 10,
      splitNumber: 3,
      splitLine: {
        lineStyle: {
          color: [
            '#cccccc'
          ]
        }
      },
      splitArea: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: '#cccccc'
        }
      },
      axisName: {
        fontSize: 10,
        color: '#666666'
      },
      indicator: data
    },
    legend: {
      data: legendData,
      bottom: '6%',
      itemStyle: {
        color: '#fca400'
      },
      borderRadius: 10,
      textStyle: {
        color: '#000',
        fontSize: 10,
      },
      selectedMode: 'single',
      itemWidth: 10,
      itemHeight: 10,
    },
    series: [{
      name: '预算 vs 开销',
      type: 'radar',
      areaStyle: {
        color: 'rgba(252, 164, 0, .2)'
      },
      lineStyle: {
        width: 1,
        color: 'rgba(252, 164, 0, 1)'
      },
      symbolSize: 2,
      symbol: 'cricle',
      data: seriesData
    }]
  };
  chart.setOption(option);
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeight: getApp().globalData.navHeight,
    navTop: getApp().globalData.navTop,
    menuHeight: getApp().globalData.menuHeight,
    tabList: ['环境因素', '思想因素', '目标因素', '能力因素'],
    currentIndex: 0,
    text: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id && options.yid) {
      this.setData({
        id: options.id,
        yid: options.yid
      })
      this.loadData()
    } else if (options.yid) {
      this.setData({
        yid: options.yid
      })
      this.loadData()
    }
    if (options.title) {
      this.setData({
        yTitle: options.title
      })
    }
  },
  async loadData() {
    wx.showLoading({
      title: '加载中',
    })
    const {
      yid,
      id
    } = this.data
    const params = {
      reviewId: yid,
    }
    if (id) {
      params.id = id
    }
    const {
      result
    } = await reviewDetail(params)
    wx.hideLoading()
    let {
      indicators,
      report
    } = result
    this.analyseData(indicators, report)

  },
  analyseData(indicators, report) {
    let data = JSON.parse(JSON.stringify(report.report))
    let label = JSON.parse(JSON.stringify(report.label))
    report.label.map((item, index) => {
      if (item.name.indexOf('综合') > -1) {
        data.splice(index, 1)
        label.splice(index, 1)
      }
    })
    let indicatorList = []
    for (let key in indicators) {
      indicatorList.push(indicators[key])
    }
    this.setData({
      reportList: data,
      labelList: label,
      comprehensiveData: report.label[0],
      indicators,
      indicatorList
    })
    let score = label[0].score
    this.initChart()
    this.drawProgressbg()
    this.drawCircle(score / 50)
  },
  drawProgressbg: function (id) {
    // 使用 wx.createContext 获取绘图上下文 context(该接口已经不再维护了)
    var canvasWidth = rpxTopx(220)
    var radius = Math.floor(canvasWidth / 2)
    var radiusDot = radius + 10
    var ctx = wx.createCanvasContext('canvasProgressbg')
    ctx.setLineWidth(5); // 设置圆环的宽度
    ctx.setStrokeStyle('#E6E6E6'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath(); //开始一个新的路径
    ctx.arc(radiusDot, radiusDot, radius, 0, 2 * Math.PI, false);
    //设置一个原点(100,100)，半径为100的圆的路径到当前路径
    ctx.stroke(); //对当前路径进行描边
    ctx.draw(false, () => {
      // 延迟保存图片，解决生成图片错位bug。
      setTimeout(() => {
        this.canvasToTempImage();
      }, 400);
    });
  },
  canvasToTempImage() {
    wx.canvasToTempFilePath({
      canvasId: "gg",
      success: (res) => {
        let tempFilePath = res.tempFilePath;
        this.setData({
          imagePath: tempFilePath,
        });
      }
    }, this);
  },
  drawCircle: function (step) {
    var canvasWidth = rpxTopx(220)
    var radius = Math.floor(canvasWidth / 2)
    var radiusDot = radius + 10
    var context = wx.createCanvasContext('canvasProgress');
    // 设置渐变
    var gradient = context.createLinearGradient(200, 100, 100, 200);
    gradient.addColorStop("0", "#fca400");
    gradient.addColorStop("1.0", "#fca400");

    context.setLineWidth(5);
    context.setStrokeStyle(gradient);
    context.setLineCap('round')
    context.beginPath();
    // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
    context.arc(radiusDot, radiusDot, radius, Math.PI / 2, step * Math.PI - (-Math.PI / 2), false);
    context.stroke();
    context.draw()
  },
  changeIndex(e) {
    const {
      labelList
    } = this.data
    const {
      index
    } = e.currentTarget.dataset
    let score = labelList[index].score
    this.setData({
      currentIndex: index
    })
    this.initChart()
    this.drawProgressbg()
    this.drawCircle(score / 50)
  },
  initChart() {
    const {
      reportList,
      currentIndex,
      indicators
    } = this.data
    let chartData = reportList[currentIndex].filter((item) => {
      return item.type == 'chart'
    })[0]
    this.ecComponent = this.selectComponent('#radar');
    this.ecComponent.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr, // new
      });
      let {
        categories,
        indicator,
        series
      } = chartData
      let seriesData = series.map((item) => {
        item.newData = []
        item.data.map((child) => {
          item.newData.push(parseInt(child))
        })
        return {
          name: item.name,
          value: item.newData,
        }
      })

      let indicatorData = []
      for (var i = 0; i < indicator.length; i++) {
        indicatorData.push({
          name: categories[i],
          max: 100
        })
      }
      setOption(seriesData.filter((item) => {
        return item.name == '本次'
      }), chart, indicatorData);
      this.chart = chart;
      return chart;
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})